package com.boot.netty.hello;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.java.Log;

import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * 创建一个服务
 */
@Log
public class HelloClient {
    static int port = 8080;
    public static void main(String[] args) throws InterruptedException {
//        启动器组装netty组件,启动
        new Bootstrap()
//                事件循环
                .group(new NioEventLoopGroup())
//                选择服务区的ServerSocketChannel实现
                .channel(NioSocketChannel.class)
//                决定了work能做那些事情-handler
                .handler(
//channel 代表和客户端进行数据读写的通道 初始化，负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder());//将成字符串ByteBuf
                    }
                })
                 .connect(new InetSocketAddress("127.0.0.1",port))
                .sync()
                .channel()
//                向服务器发送数据
                .writeAndFlush("hello,world");

    }
}
